<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/7
 * Time: 9:29
 */

namespace app\api\model;


use app\lib\exception\ProductException;
use app\lib\exception\ThemeException;

class Theme extends BaseModel
{
    protected $hidden = ['delete_time','topic_img_id','head_img_id'];

    public function topicImg(){
        return $this->belongsTo('Image','topic_img_id','id');
    }

    public function headImg(){
        return $this->belongsTo('Image','head_img_id','id');
    }

    /**
     * 多对多关联商品
     * @return \think\model\relation\BelongsToMany
     */
    public function products(){
        return $this->belongsToMany('Product','theme_product','product_id','theme_id');
    }

    /**
     * 获得主题下的所有商品
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getThemeWithProducts($id){
        $themes = self::with('products,topicImg,headImg')->find($id);
        return $themes;
    }

    /**
     * 获取主题列表
     * @param $ids
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public static function getThemeList($ids){
        if(empty($ids)){
            return [];
        }
        $themes = self::with('products')->select($ids);
        return $themes;
    }

    /**
     * 新增主题下的商品
     * @param $themeID
     * @param $productID
     * @return bool
     */
    public static function addThemeProduct($themeID,$productID){
        $models = self::checkRelationExist($themeID,$productID);
        // 写入中间表，这里要注意，即使中间表已存在相同的themeID和itemID数据
        // 虽然写入不成功，但是TP并不会报错，最好是在插入之前先判断
        $models['theme']->products()->attach($productID);
        return true;
    }

    /**
     * 删除指定主题下的商品
     * @param $themeID
     * @param $productID
     * @return bool
     */
    public static function deleteThemeProduct($themeID,$productID){
        $models = self::checkRelationExist($themeID,$productID);
        $models['theme']->products()->detach($productID);
        return true;
    }

    /**
     * 检测主题和商品是否都存在
     * @param $themeID
     * @param $productID
     * @return array
     * @throws ProductException
     * @throws ThemeException
     */
    private static function checkRelationExist($themeID,$productID){
        $theme = self::get($themeID);
        if(!$theme){
            throw new ThemeException();
        }
        $product = Product::get($productID);
        if(!$product){
            throw new ProductException();
        }
        return [
            'theme' => $theme,
            'product' => $product
        ];
    }
}